const Sequelize=require('sequelize');
const config=require('./config');

var sequelize=new Sequelize(config.database,config.username,config.password,
{
    host:config.host,
    dialect:'mysql',
    pool:
    {
        max:5,
        min:0,
        idle:3000
    }
});
//定义模型Pet,与数据库的pet表进行栏位映射
var Pet=sequelize.define('pet',
{
    id:
    {
        type:Sequelize.STRING(50),
        primaryKey:true
    },
    name:Sequelize.STRING(100),
    gender:Sequelize.BOOLEAN,
    birth:Sequelize.STRING(100),
    createdAt:Sequelize.BIGINT,
    updatedAt:Sequelize.BIGINT,
    version:Sequelize.BIGINT
},
{
    timestamps:false     //关闭Sequelize的自动添加timestamp的功能
});

var now = Date.now();
console.log(now);
Pet.create({
    id: 'g-' + now,
    name: 'Gaffey',
    gender: false,
    birth: '2007-07-07',
    createdAt: now,
    updatedAt: now,
    version: 0
}).then(function (p) {
    console.log('created.' + JSON.stringify(p));
}).catch(function (err) {
    console.log('failed: ' + err);
});



//插入 await方式
(async ()=>
{
    var dog= await Pet.create(
    {
        id:'d-'+now,
        name:'Odie',
        gender:false,
        birth:'2017-08-03',
        createdAt:now,
        updatedAt:now,
        version:0
    });
    console.log('create:'+JSON.stringify(dog));
})();
//查询

(async ()=>
{
    var pets= await Pet.findAll();
    console.log(`找到了${pets.length}个pets`);
    for(let p of pets)
    {
        console.log(JSON.stringify(p));
    }
    
})();

//修改
(async ()=>
{
    //findAll查询返回一个对象数组
    var p=await Pet.findAll({where:{name:"Gaffey"}});
    p[0].gender=1;
    p[0].updateAt=Date.now();
    p[0].version++;
    await p[0].save();
})();


//删除
(async ()=>
{
    //find返回一个对象
    var p= await Pet.find({where:{name:"Odie"}});
    await p.destroy();
})();
